﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;

namespace FastShip88.Admin
{
    public partial class AdmParcelCombine : System.Web.UI.Page
    {
        DBAccess.UsersDataContext db;
        string mCurCommandName;

        protected void Page_Load(object sender, EventArgs e)
        {
            db = new DBAccess.UsersDataContext();

            lblError.Visible = false;
            lblSuccess.Visible = false;
            mCurCommandName = "";

            if (!IsPostBack)
            {
                init_data();
                div_results.Visible = true;
                div_sub.Visible = false;
                div_selected.Visible = false;

            }

        }

        protected void fvSelected_PreRender(object sender, EventArgs e)
        {

        }

        protected void init_data()
        {

            var parcels = from p in db.ParcelInfos
                          where p.StatusId == 77 /*新包裹合并*/
                          orderby p.UserId
                          select new { p.Id, p.UserId, p.ParcelNo, p.ShopId, p.Description, p.Weight, p.ArriveDate,  UserName = (p.UserInfo.LastName + p.UserInfo.FirstName) };

            gvResults.DataSourceID = null;
            gvResults.DataSource = parcels;
            gvResults.DataBind();

            gvResults.SelectedIndex = -1;

        }

        protected void init_gvParcel_data()
        {
            int p_id = SafeConvert.ToInt(gvResults.SelectedDataKey.Value);

            var parcels = from p in db.ParcelInfos
                          where p.ToId == p_id /*新包裹合并*/
                          orderby p.UserId
                          select new { p.Id, p.UserId, p.ParcelNo, p.ShopId, ShopName = p.ShopInfo.name, p.Description, p.Weight, p.ArriveDate };

            gvParcel.DataSourceID = null;
            gvParcel.DataSource = parcels;
            gvParcel.DataBind();
        }

        protected void gvResults_SelectedIndexChanged(object sender, EventArgs e)
        {

            div_sub.Visible = true;
            div_selected.Visible = true;

            gvSub.DataBind();
            init_gvParcel_data();
            fvSelected.ChangeMode(FormViewMode.Edit);
        }



        protected void fvSelected_ItemCommand(object sender, FormViewCommandEventArgs e)
        {

            if (e.CommandName == "Update")
            {
                switch (e.CommandArgument.ToString())
                {
                    case "Complete":
                        mCurCommandName = e.CommandArgument.ToString();
                        break;
                    case "Fail":
                        string strMemo = ((TextBox)fvSelected.FindControl("txtMemo")).Text.Trim();
                        if (strMemo.Length == 0)
                        {
                            lblError.Text = "请将失败理由填入系统备注";
                            lblError.Visible = true;
                            mCurCommandName ="FailCancel";
                        }
                        else
                            mCurCommandName = e.CommandArgument.ToString();
                        break;
                    default:
                        mCurCommandName = "Update";
                        break;
                }
            }

        }


        protected void gvResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvResults.PageIndex = e.NewPageIndex;
            init_data();
        }

        protected void SqlDataSource1_Updated(object sender, SqlDataSourceStatusEventArgs e)
        {
            gvSub.DataBind();
            lblSuccess.Visible = true;

           if (mCurCommandName == "Complete" || mCurCommandName == "Fail")
           {
                int parcelId = SafeConvert.ToInt(gvResults.SelectedValue);
                int userId = Utility.GetUserId(this);
                byte statusId = 0, newStatusId = 0;

                if (mCurCommandName == "Complete")
                {
                    statusId = 70; //合并完成
                    newStatusId = 78; //新合并包裹完成
                }

                if (mCurCommandName == "Fail")
                {
                    statusId = 75; //合并取消
                    newStatusId = 79; //新合并包裹取消
                }


                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        var q_subs = from s in db.SubParcels
                                     where s.ToId == parcelId
                                     select s;
                        foreach (var q_sub in q_subs)
                        {
                            if (mCurCommandName == "Complete")
                            {
                                q_sub.CombineDate = DateTime.Now;
                                q_sub.CombineUserId = userId;
                            }
                            else //Combine Fail
                            {
                                string strMemo = q_sub.Memo == null ? "" : q_sub.Memo.Trim();
                                strMemo += " CombineFail for new parcel:" + parcelId.ToString();
                                if (strMemo.Length > 64)
                                {
                                    strMemo = strMemo.Substring(0, 64);
                                    Utility.Log(Utility.LogLevel.Error, "Memo field is overlength for SubParcels Table (id:" + q_sub.Id.ToString() + ")");
                                }
                                q_sub.Memo = strMemo;
                                q_sub.ToId = null;
                            }
                        }

                        db.SubmitChanges();

                        var q_parcels = from s in db.ParcelInfos
                                     where s.ToId == parcelId
                                     select s;
                        foreach (var q_parcel in q_parcels)
                        {
                            if (mCurCommandName == "Complete")
                            {
                                q_parcel.CombineDate = DateTime.Now;
                                q_parcel.CombineUserId = userId;
                                q_parcel.StatusId = statusId;
                            }
                            else //Combine Fail
                            {
                                string strMemo = q_parcel.Memo == null ? "" : q_parcel.Memo.Trim();
                                strMemo += " CombineFail for new parcel:" + parcelId.ToString();
                                if (strMemo.Length > 64)
                                {
                                    strMemo = strMemo.Substring(0, 64);
                                    Utility.Log(Utility.LogLevel.Error, "Memo field is overlength for ParcelInfos Table (id:" + q_parcel.Id.ToString() + ")");
                                }
                                q_parcel.Memo = strMemo;
                                q_parcel.StatusId = statusId;
                                q_parcel.ToId = null;
                            }
                        }

                        db.SubmitChanges();


                        var q = (from p in db.ParcelInfos where p.Id == parcelId select p).First();

                        q.StatusId = newStatusId;
                        db.SubmitChanges();


                        lblSuccess.Visible = true;
                   }
                    catch (Exception ex)
                    {
                        lblError.Text = ex.Message;
                        lblError.Visible = true;

                        return;
                    }
                        
                    ts.Complete();



                }

                if (!lblError.Visible)
                {
                    init_data();
                    div_sub.Visible = false;
                    div_selected.Visible = false;

                    int parcelUserId;
                    var q_parcel = (from p in db.ParcelInfos where p.Id == parcelId select p).First();
                    parcelUserId = SafeConvert.ToInt(q_parcel.UserId);

                    if (mCurCommandName == "Complete")
                    {
                        Utility.SendEmail(Utility.EmailTypes.ParcelCombineComplete, parcelUserId, parcelId.ToString());

                        decimal unitPrice5 = Utility.GetUnitPriceByFeeType(5, parcelUserId); //合并服务收费
                        decimal unitPrice4 = Utility.GetUnitPriceByFeeType(4, userId); //分拆服务收费

                        var q_bill = new DBAccess.UserBill();
                        q_bill.UserId = userId;
                        q_bill.FeeTypeId = 5; //合并服务
                        q_bill.Date = DateTime.Now;
                        q_bill.IsCancelled = false;
                        q_bill.IsCleared = false;
                        q_bill.Quantity = (int)(q_parcel.Weight.Value + 0.7); //超过0.3即算一磅。
                        q_bill.Amount = (decimal)q_bill.Quantity.Value * (unitPrice5+ unitPrice4);  //分拆和合并一起计费
                        q_bill.ParcelId = parcelId;

                        db.UserBills.InsertOnSubmit(q_bill);
                        db.SubmitChanges();


                    }

                    if (mCurCommandName == "Fail")
                    {
                        Utility.SendEmail(Utility.EmailTypes.ParcelCombineFail, parcelUserId, parcelId.ToString());
                    }


                }


 
            }


        }

        protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
        {
            

            switch (mCurCommandName)
            {
                case "Complete":
                case "Fail":
                    int userId = Utility.GetUserId(this);
                    e.Command.Parameters["@CombineDate"].Value = DateTime.Now;
                    e.Command.Parameters["@CombineUserId"].Value = userId;
                    break;
                case "FailCancel":
                    e.Cancel= true;
                    break;
            }

        }
    }
}
